const ItemModel = require('../models/itemModel');
const UserModel = require('../models/userModel'); // 引入 UserModel

const getAllItems = async (req, res) => {
  try {
    const items = await ItemModel.getAllItems();
    res.status(200).json(items);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const getItemById = async (req, res) => {
  try {
    const item = await ItemModel.getItemById(req.params.id);
    if (!item) {
      return res.status(404).json({ error: 'Item not found' });
    }
    res.status(200).json(item);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const getItemByUserId = async (req, res) => {
  try {
    const userId = req.query.userId; // 使用 req.query 获取查询参数
    console.log(req);
    console.log(userId);
    const items = await ItemModel.getItemByUserId(userId);
    if (!items.length) {
      return res.status(404).json({ error: 'No items found for this user' });
    }
    res.status(200).json(items);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const addItem = async (req, res) => {
  try {
    const newItem = req.body;
    const userId = req.user.id; // 从请求中获取用户ID
    const user = await UserModel.getUserById(userId); // 获取用户信息

    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    const itemWithUserDetails = {
      ...newItem,
      user_id: userId,
      owner_name: user.name,
      owner_contact: user.contact
    };

    // 检查是否有图片 URL
    if (newItem.product_image) {
      itemWithUserDetails.product_image = newItem.product_image;
    }

    const insertedItem = await ItemModel.addItem(itemWithUserDetails);
    res.status(201).json(insertedItem[0]);
  } catch (error) {
    console.error(error); // 打印错误信息，方便调试
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

// 定义一个函数来转换日期格式
const convertToMySQLDateTime = (date) => {
  if (!date) return null;
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const updateItem = async (req, res) => {
  try {
    const updatedItem = req.body;
    const userId = req.user.id; 
    const itemId = req.params.id;

    // 检查商品是否存在
    const existingItem = await ItemModel.getItemById(itemId);
    if (!existingItem) {
      return res.status(404).json({ error: 'Item not found' });
    }

    // 创建只包含允许更新字段的对象
    const updateData = {
      product_name: updatedItem.product_name || existingItem.product_name,
      product_description: updatedItem.product_description ?? existingItem.product_description,
      product_price: updatedItem.product_price !== undefined ? Number(updatedItem.product_price) : existingItem.product_price,
      product_image: updatedItem.product_image || existingItem.product_image,
      updated_at: convertToMySQLDateTime(new Date()) // 强制更新时间
    };

    // 验证价格是否为有效正数
    if (isNaN(updateData.product_price) || updateData.product_price <= 0) {
      return res.status(400).json({ error: '商品价格必须为有效正数' });
    }

    // 执行更新
    const result = await ItemModel.updateItem(itemId, updateData);
    if (result.length === 0) {
      return res.status(404).json({ error: 'Item not found' });
    }

    // 返回更新后的完整数据
    const updatedItemDetails = await ItemModel.getItemById(itemId);
    res.status(200).json(updatedItemDetails);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const deleteItem = async (req, res) => {
  try {
    const userId = req.user.id; // 从请求中获取用户ID
    const itemId = req.params.id;

    // 检查商品是否存在
    const existingItem = await ItemModel.getItemById(itemId);
    if (!existingItem) {
      return res.status(404).json({ error: 'Item not found' });
    }

    // 删除商品
    const result = await ItemModel.deleteItem(itemId);
    if (result.length === 0) {
      return res.status(404).json({ error: 'Item not found' });
    }

    // 返回删除成功的消息
    res.status(200).json({ message: 'Item deleted successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

module.exports = { getAllItems, getItemByUserId, getItemById, addItem, updateItem, deleteItem };